package com.xn.monitor.web.notify.websocket;

import com.alibaba.fastjson.JSON;
import com.xn.monitor.common.Constants;
import com.xn.monitor.entity.ServerEventInfo;
import com.xn.monitor.web.entity.Environment;
import com.xn.monitor.web.entity.SessionHolder;
import com.xn.monitor.web.notify.NotifyService;
import com.xn.monitor.web.service.MonitorService;
import com.xn.monitor.web.service.SpringContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * websocket通知服务
 *
 * Created by yangshoujun on 2017/7/19 下午5:12.
 */
@Service
public class MonitorWebSocketHandler implements WebSocketHandler, InitializingBean, NotifyService {

    private static Map<WebSocketSession, SessionHolder> sessions = new ConcurrentHashMap<WebSocketSession, SessionHolder>();

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        SessionHolder holder = new SessionHolder();
        holder.setSession(session);
        holder.access();
        sessions.put(session, holder);
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        SessionHolder holder = sessions.get(session);
        if(holder != null) {
            holder.access();
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable throwable) throws Exception {
        if(session.isOpen()){
            session.close();
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        SessionHolder holder = sessions.get(session);
        if(holder != null) {
            sessions.remove(session);
        }
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
        // 定时清除过期session
        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                Iterator<SessionHolder> iter = sessions.values().iterator();
                for(;iter.hasNext();) {
                    SessionHolder holder = iter.next();
                    WebSocketSession session = holder.getSession();
                    if(session == null) {
                        iter.remove();
                    }

                    long time = System.currentTimeMillis();
                    if(time - holder.getLastAccessTime() > Constants.SESSION_EXPIRE_TIME) {
                        iter.remove();
                        try {
                            session.close();
                        } catch (IOException e) {
                            logger.error(e.toString(), e);
                        }
                    }
                }
            }
        }, 3 * 1000, 5 * 1000, TimeUnit.MILLISECONDS);
    }

    public void notify(ServerEventInfo eventObject) {
        MonitorService monitorService = SpringContext.getBean(MonitorService.class);
        List<Environment> envs = monitorService.getEnviroments();
        for(SessionHolder holder : sessions.values()) {
            WebSocketSession session = holder.getSession();
            if(session != null && session.isOpen()) {
                try {
                    session.sendMessage(new TextMessage(JSON.toJSONString(envs)));
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }

}
